home *** CD-ROM | disk | FTP | other *** search
- Path: unix.sri.com!usenet
- From: mklenk@updike.sri.com (Mark Klenk)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: 19 Jan 1996 21:33:44 GMT
- Organization: SRI International
- Message-ID: <4dp2no$3va@unix.sri.com>
- References: <4dorr8$i58@cloner3.netcom.com>
- Reply-To: mklenk@updike.sri.com
- NNTP-Posting-Host: 204.75.161.40
-
-
- Andrew Snyder wrote:
- >
- > Bill Simpson wrote:
- >>
- >>Is there a fast way to decide whether a number n is a power of 2?
- >
- >no tricks
- >
- >#define ISPOW2(x) (((x) & 1) ^ 1)
-
- He asked for POWER of 2, not MULTIPLE.
-
- Your macro will return non-zero for 6, for example,
- which is not a power of 2.
-
- I don't think there is any way to do it other than
- recursively or iteratively.
-
- int
- NumIsPowerOf2(int num)
- {
- if (num <= 0) {
- return 0;
- }
-
- while (num > 0) {
- if ((num & 1) && num > 1) {
- return 0;
- }
- num >>= 1;
- }
-
- return 1;
- }
-
- ---
-
- mklenk@coronacorp.com (Mark Klenk)
-
-
-
-